package com.iwat.spring.aop.util;

/**
 * @Author wangweiqiang
 * @Classname RedisBlockingQueueService
 * @Date 2023/9/23 10:59
 * @Description
 */

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisBlockingQueue<T> {

    private final RedisTemplate<String, T> redisTemplate;

    @Autowired
    public RedisBlockingQueue(RedisTemplate<String, T> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 将元素添加到队列尾部
     *
     * @param key
     * @param value
     */
    public void enqueue(String key, T value) {
        redisTemplate.opsForList().rightPush(key, value);
    }

    /**
     * 从队列头部获取元素（阻塞方式，直到有元素可用）
     *
     * @param key
     * @return
     */
    public T dequeue(String key) {
        //没有消息就阻塞在这里，直到有消息为止
        return redisTemplate.opsForList().leftPop(key, 60 * 60 * 24 * 31, TimeUnit.SECONDS);
    }
}
